# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from elasticsearchLib.ElasticSearchClient import BLogElasticSearchClient
from rest_framework.views import APIView
from blog.models import BlogMsg
from rest_framework.response import Response
from blog.serializer import BlogMsgSerializer
from rest_framework import status


# Create your views here.


class BlogSearchView(APIView):

    def post(self, request, format=None):
        es_client = BLogElasticSearchClient()
        es_client.rebuild_index()
        es_client.bulk_index_data()
        return Response({'result': 'OK'}, status=status.HTTP_200_OK)

    def get(self, request, format=None):
        key_word = request.GET.get("q", "")
        page = request.GET.get("page", "1")

        es_client = BLogElasticSearchClient()
        response = es_client.search(key_words=key_word,
                                    orign=(int(page) - 1) * 5,
                                    to=int(page) * 5)
        blog_list = BlogMsg.objects.filter(pk__in=response.keys())
        for blog in blog_list:
            es_blog = response[blog.id]
            if 'content' in es_blog:
                blog.blog_content = es_blog['content'][0]
            if 'title' in es_blog:
                blog.title = es_blog['title'][0]

        serializer = BlogMsgSerializer(data=blog_list, many=True)
        serializer.is_valid()
        return Response(serializer.data)
